﻿var connect = require('gulp-connect');
var proxy = require('http-proxy-middleware');
var gutil = require('gulp-util');
var gulp = require('gulp'),
    minifyCss = require('gulp-minify-css'),
    uglify = require('gulp-uglify'),
    clean = require('gulp-clean'),
    replace = require('gulp-replace'),//�ļ����滻���ο���https://www.npmjs.com/package/gulp-replace
    rename = require("gulp-rename"),
    rev = require('gulp-rev'),
    //revReplace = require('gulp-rev-replace'),
    autoprefixer = require('gulp-autoprefixer'),
    imagemin = require('gulp-imagemin'),
    useref = require('gulp-useref'),
    runSequence = require('run-sequence'),
    htmlmin = require('gulp-htmlmin'),//ѹ��html
    revCollector = require('gulp-rev-collector');
var assetsPublicPath ='./src';
var port = 8089;
var process = require('process');
var sh = require('shelljs');
var target_api ='http://192.168.0.140:8080';
var target_api_abs ='http://192.168.0.140:8080';
//����ļ��У�������Դ����?
gulp.task('clean',function(){
    return gulp.src(assetsPublicPath).pipe(clean());
});

//css��������
gulp.task('minifyCss',['minifyCss1','minifyCss2']);
gulp.task('minifyCss1',function(){
    return  gulp.src(['./dev/css/**/*.css'])
        .pipe(autoprefixer())
        .pipe(minifyCss())
        .pipe(rev())
        .pipe(gulp.dest(assetsPublicPath+'/css'))
        .pipe(rev.manifest())
        .pipe(gulp.dest(assetsPublicPath+'/rev/css1'));
});
gulp.task('minifyCss2',function(){
    return  gulp.src(['./dev/frame/static/css/style.css'])
        .pipe(autoprefixer())
        .pipe(minifyCss())
        .pipe(rev())
        .pipe(gulp.dest(assetsPublicPath+'/frame/static/css'))
        .pipe(rev.manifest())
        .pipe(gulp.dest(assetsPublicPath+'/rev/css2'));
});
//js��������
gulp.task('minifyJs',['minifyJs1','minifyJs2']);
gulp.task('minifyJs1',function(){
    return  gulp.src(['./dev/js/**/*.js'])
        .pipe(uglify({
            ie8:true,
            mangle: false//���ͣ�Boolean Ĭ�ϣ�true �Ƿ��޸ı�����
        }))
        .on('error', function (err) {
            gutil.log(gutil.colors.red('[Error]'), err.toString());
        })
        .pipe(rev())
        .pipe(gulp.dest(assetsPublicPath+'/js'))
        .pipe(rev.manifest())
        .pipe(gulp.dest(assetsPublicPath+'/rev/js1'));
});
gulp.task('minifyJs2',function(){
    return  gulp.src(['./dev/frame/layui/layui.js'])
        .pipe(uglify({
            ie8:true,
            mangle: false
        }))
        .pipe(rev())
        .pipe(gulp.dest(assetsPublicPath+'/frame/layui'))
        .pipe(rev.manifest())
        .pipe(gulp.dest(assetsPublicPath+'/rev/js2'));
});

//·���滻����
gulp.task('rev',function(){
    return  gulp.src([assetsPublicPath+'/rev/**/*.json',assetsPublicPath+'/**/*.html'])
    .pipe(revCollector())
    //     .pipe(revCollector({
    //         replaceReved:true          //һ��Ҫ������һ�䣬��Ȼ�����滻����һ�ε�ֵ
    //     }))
        .pipe(gulp.dest(assetsPublicPath));
});
//json��
gulp.task('copyJson', function() {
    return gulp.src(['./dev/json/**/*'])
        .pipe(gulp.dest(assetsPublicPath+'/json'));
});
//html
gulp.task('copyHtml', function() {
    var options = {
        removeComments: true,//���HTMLע��
        collapseWhitespace: true,//ѹ��HTML
        collapseBooleanAttributes: true,//ʡ�Բ������Ե�ֵ <input checked="true"/> ==> <input />
        removeEmptyAttributes: true,//ɾ�����пո�������ֵ <input id="" /> ==> <input />
        removeScriptTypeAttributes: true,//ɾ��<script>��type="text/javascript"
        removeStyleLinkTypeAttributes: true,//ɾ��<style>��<link>��type="text/css"
        minifyJS: true,//ѹ��ҳ��JS
        minifyCSS: true//ѹ��ҳ��CSS
    };
    return gulp.src(['./dev/**/*.html'])
        // .pipe(htmlmin(options))
        .pipe(gulp.dest(assetsPublicPath));
});
gulp.task('copyFrame',['frame_js','frame_css','frame_images','copyFonts']);
gulp.task('frame_js', function() {
    return gulp.src(['./dev/frame/**/*.js','!./dev/frame/layui/layui.js'])
        .pipe(uglify({
                ie8:true,
                mangle: false
            }))
        .pipe(gulp.dest(assetsPublicPath+'/frame/'));
});
gulp.task('frame_css', function() {
    return gulp.src(['./dev/frame/**/*.css','!./dev/frame/static/css/style.css'])
        // .pipe(autoprefixer())
        .pipe(minifyCss())
        .pipe(gulp.dest(assetsPublicPath+'/frame/'));
});
gulp.task('frame_images', function() {
    return gulp.src(['./dev/frame/**/*.{jpg,png,gif}'])
        .pipe(imagemin())
        .pipe(gulp.dest(assetsPublicPath+'/frame/'));
});
gulp.task('copyFonts', function () {
    return gulp.src('./dev/frame/layui/font/*')
        .pipe(gulp.dest(assetsPublicPath+'/frame/layui/font/'))
})
gulp.task('default', ['clean'], function(){
    // gulp.start('mini-css','mini-js','rev');
    console.time('buildTime');
   return gulp.start('build',function () {
       console.timeEnd('buildTime');
   });
});
//��ʽ����
gulp.task('build', function (done) {
    runSequence(
        ['minifyCss'],
        ['minifyJs'],
        ['copyJson'],
        ['copyHtml'],
        ['copyFrame'],
        ['rev'],
        done);
});

gulp.task('server',['open-browser'], function() {
	var rootPath ='./dev'
    connect.server({
        //root: ['dev'],
		root:rootPath,
        port: port,
        livereload: true,
        middleware: function(connect, opt) {
            return [
			
                proxy('/api',  {
                    target: target_api,
                    changeOrigin:true,
						 pathRewrite: {
							'^/api' : '/api',     // rewrite path 
							
						}
                }),
				
			 	proxy('/Abs',  {
                    target: target_api_abs,
                    changeOrigin:true,
						 pathRewrite: {
							'^/Abs' : '/api',     // rewrite path
						 }
                }),
				
				proxy('/upload',  {
                    target: ' ',
                    changeOrigin:true,
						 pathRewrite: {
							'^/upload' : '/upload',     // rewrite path 
						}
                })
            ]
        }
	
 });
	gulp.watch('./dev/**/*', ['reload']);
})
gulp.task('reload',function(){
	connect.reload();
});
gulp.task('open-browser', function () {
    var platform = process.platform;
    var shellStr1 = "open -a '/Applications/Google Chrome.app' 'http://localhost:"+port+"/main.html'";
    var shellStr2 = "start http://localhost:"+port+"/main.html";
    // �������������?
    var openFunc = function (str, flag) {
        // ִ�в����쳣����
        if (sh.exec(str).code !== 0) {
            sh.echo(flag + '�´������ʧ��?,��������װchrome����ΪĬ�������?!');
            sh.exit(1);
        }
    };
    if (platform === 'darwin') {
        openFunc(shellStr1, 'Mac');
    } else if (platform === 'win32' || platform === 'win64') {
        openFunc(shellStr2, 'Windows');
    } else {
        sh.echo('����ֻ֧��Mac��windowsϵͳ!���δ��ҳ�棬��ȷ�ϰ�װchrome����ΪĬ�������?!');
    }
});
